package com.wwj.server.game;

import com.wwj.core.server.entity.GameServer;
import com.wwj.core.server.service.IGameServerService;
import com.wwj.server.codc.MessageDecoder;
import com.wwj.server.codc.MessageEncoder;
import com.wwj.utils.IpUtil;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class Server {

    private Logger logger = LoggerFactory.getLogger(getClass());

//    @Value("#{resourceProperties['game_server.server_name']}")
//    private String serverName;
//
//    @Value("#{resourceProperties['game_server.port']}")
//    private int port;

    @Resource
    private IGameServerService gameServerService;

    /**
     * 启动
     */
    public void start(String serverName, int port) {

        // 服务类
        ServerBootstrap b = new ServerBootstrap();

        // 创建boss和worker
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            // 设置循环线程组事例
            b.group(bossGroup, workerGroup);

            // 设置channel工厂
            b.channel(NioServerSocketChannel.class);

            // 设置管道
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addLast(new MessageEncoder());
                    ch.pipeline().addLast(new MessageDecoder());
                    ch.pipeline().addLast(new ServerHandler());

                }
            });

            b.option(ChannelOption.SO_BACKLOG, 2048)// 链接缓冲池队列大小
                    .childOption(ChannelOption.SO_KEEPALIVE, true);// 启用心跳保活机制


            // 绑定端口
            b.bind(port).sync();

            GameServer gameServer = gameServerService.findByServerName(serverName);
            if (null == gameServer) {
                gameServer = new GameServer(serverName, IpUtil.getHostIp(), port);
                gameServerService.createNewServer(gameServer);
            } else {
                gameServer.setIp(IpUtil.getHostIp());
                gameServer.setPort(port);
                gameServer.setIsOnline(GameServer.ONLINE);
                gameServerService.updateServer(gameServer);
            }
            logger.info("GameServer服务端已启动,监听端口：{}", port);

            //关闭服务器后调用
            final GameServer server = gameServer;
            Runtime.getRuntime().addShutdownHook(new Thread() {
                @Override
                public void run() {
                    try {
                        server.setIsOnline(GameServer.OFFLINE);
                        gameServerService.updateServer(server);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

        } catch (Exception e) {
            logger.error("GameServer服务端启动异常：", e);
        }
    }

}
